﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using TravelSite.Entities;
using Dapper;

namespace TravelSite.DAL.Repositories
{
    public class WholesalerRepository : BaseRepository<Wholesaler>
    {
        protected override string TableName
        {
            get { return "[Wholesalers]"; }
        }

        public override IEnumerable<Wholesaler> FindAll()
        {
            string strSQL = @"  select vo.WholesalerId, vo.WholesalerName, vo.IsDefault, 
                    convert(bit, case 
                                    when 1 = 0 then 0
                                else 1 end) as CanDelete
                    from [Wholesalers] (nolock) as vo 
                    order by vo.WholesalerName ";

            IEnumerable<Wholesaler> result = Connection.Query<Wholesaler>(strSQL);
            return result;
        }

        public override Wholesaler Find(int id)
        {
            Wholesaler result = Connection.Query<Wholesaler>(
                @"  select vo.WholesalerId, vo.WholesalerName, vo.IsDefault
                    from [Wholesalers] (nolock) as vo
                    where vo.WholesalerId = @WholesalerId", new { WholesalerId = id }).SingleOrDefault();
            return result;
        }

        public override void Insert(Wholesaler item)
        {
            if (item.IsDefault)
                Connection.Execute(@"update Wholesalers set IsDefault = 0");

            Connection.Execute(
                @"insert into [Wholesalers] 
                (WholesalerName, IsDefault)
                values (@WholesalerName, @IsDefault)", item);
        }

        public override void Update(Wholesaler item)
        {
            if (item.IsDefault)
                Connection.Execute(@"update Wholesalers set IsDefault = 0");

            Connection.Execute(
                @"update Wholesalers
                    set WholesalerName = @WholesalerName, IsDefault = @IsDefault
                    where (WholesalerId = @WholesalerId)", item);
        }

        public override void Delete(int id)
        {
            Connection.Execute(
                @"delete 
                    from Wholesalers
                    where (WholesalerId = @WholesalerId)", new { WholesalerId = id });
        }

    }
}
